//
//  DTCBluetoothDataBaseManager.h
//  BluetoothProject
//
//  Created by JianWei Chen on 16/9/5.
//  Copyright © 2016年 JianWei Chen. All rights reserved.
//


#import "FMDB.h"
#import "DTCBluetooth.h"


#define TableName @"BluetoothDeviceTable"
#define DateBaseFileName @"DTCBluetoothDataBaseManager.db"

@interface DTCBluetoothDataBaseManager()

@property (nonatomic, strong) FMDatabaseQueue *databasequeue;//为了数据库的操作安生，采用线程安生的数据库来进行数据库管理

@end

@implementation DTCBluetoothDataBaseManager

#pragma mark - 初始化
+ (DTCBluetoothDataBaseManager*)sharedInstance
{
    static DTCBluetoothDataBaseManager* static_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        static_manager = [[DTCBluetoothDataBaseManager alloc] init];
        NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        path = [path stringByAppendingPathComponent:DateBaseFileName];
        static_manager.databasequeue = [FMDatabaseQueue databaseQueueWithPath:path] ;
        [static_manager createtablae:TableName];
    });
    return static_manager;
}

#pragma mark - 事件处理

/**
 建表
 */
- (BOOL)createtablae:(NSString *)tableName
{
    __block BOOL success = NO;
    [self.databasequeue inDatabase:^(FMDatabase *db) {
        [db open];
        
        
        NSString *sql=[NSString stringWithFormat:@"create table if not exists %@(mac text primary key,dataID text,deviceID text,localName text,customName text,password text,peripheralUUID text)",tableName];
        success= [db executeUpdate:sql];
        [db close];
    }];
    NSLog(@"tablename%@建立",tableName);
    return success;
}

- (NSArray *)allDeviceWithMac:(NSString *)mac
{
    NSMutableArray *temarry=[[NSMutableArray alloc]init];
    
    NSArray *allDeviceList = [self getAllDevice];
    
    for (DTCDeviceModel *device in allDeviceList) {
        if ([device.mac.lowercaseString isEqualToString:mac.lowercaseString]) {
            [temarry addObject:mac];
        }
    }
    return temarry;
}

- (NSArray *)getAllDevice
{
    NSMutableArray *temarry=[[NSMutableArray alloc]init];
    
    [self.databasequeue inDatabase:^(FMDatabase *db) {
        [db open];
        
        NSString *sql= [NSString stringWithFormat:@"SELECT * FROM %@ ",TableName];
        FMResultSet *set = [db executeQuery:sql];
        while ([set next]){
            DTCDeviceModel *device=[[DTCDeviceModel alloc]init];
            device.mac = [set stringForColumn:@"mac"];
            device.dataID = [set stringForColumn:@"dataID"];
            device.deviceID = [set stringForColumn:@"deviceID"];
            device.localName = [set stringForColumn:@"localName"];
            device.customName = [set stringForColumn:@"customName"];
            device.password = [set stringForColumn:@"password"];
            device.peripheralUUID = [set stringForColumn:@"peripheralUUID"];
            
            for (DTCDeviceModel *obc in [DTCBluetoothManager shareInstance].scanDeviceList) {//外设匹配
                if ([obc.mac isEqualToString:device.mac]) {
                    device.currentPeripheral =obc.currentPeripheral;
                    break;
                }
            }
            [temarry addObject:device];
        }
        [db close];
    }];
    return temarry;
}


- (BOOL)addDevice:(DTCDeviceModel *)device
{
    __block BOOL success = NO;
    
    [self deleteDeviceWithMac:device.mac];
    
    [self.databasequeue inDatabase:^(FMDatabase *db) {
        [db open];
        
        NSString *sql= [NSString stringWithFormat:@"insert into %@(mac,dataID,deviceID,localName,customName,password,peripheralUUID) values (?,?,?,?,?,?,?)",TableName];
        success = [db executeUpdate:sql,device.mac,device.dataID,device.deviceID,device.localName,device.customName,device.password,device.peripheralUUID];
        
        [db close];
    }];
    
    if (success) {
        NSLog(@"添加成功");
    }else{
        NSLog(@"添加成功");
    }
    
    return success;
}

- (void)deleteAllDevice
{
    __block BOOL success = NO;
    
    
    [self.databasequeue inDatabase:^(FMDatabase *db) {
        [db open];
        
        NSString *sql= [NSString stringWithFormat:@"delete from %@ ",TableName];
        success = [db executeUpdate:sql];
        
        [db close];
    }];
}

- (BOOL)deleteDeviceWithMac:(NSString *)mac
{

    __block BOOL success = NO;
    
    [self.databasequeue inDatabase:^(FMDatabase *db) {
        [db open];
        
        NSString *sql= [NSString stringWithFormat:@"delete from %@ where mac=?",TableName];
        success = [db executeUpdate:sql,mac];
        
        [db close];
    }];
    
    return success;
}

@end
